<template>
  <el-container>
    <basic-crud :option="option" ref="basicCrudRef" businessUrl="/permission/roleController"
      :apiAddParams="{ roleLevel: 'normal' }" selectType="radio">
      <template #menu-left>
        <el-button icon="el-icon-plus" :loading="relationMenuOpenBtnLoading" @click="handleOpenRelationMenuDialog"
          plain type="primary">关联菜单</el-button>
        <el-button icon="el-icon-plus" :loading="relationUserOpenBtnLoading" plain type="primary"
          @click="handleOpenRelationUserDialog">关联用户</el-button>
      </template>
    </basic-crud>
    <basic-dialog v-model="relationMenuVisible" title="菜单权限" width="600" :submitBtnLoading="relationMenuSubmitLoading"
      :autoClose="false" @submit="handleRelationMenuSubmit">
      <el-tree style="max-height: 60vh; overflow: auto" ref="menuTreeRef" :data="menuList" node-key="id"
        :props="{ children: 'children', label: 'name' }" show-checkbox check-strictly @check="handleMenuSelectChange" />
    </basic-dialog>
    <basic-dialog-table v-model="relationUserVisible" :defaultSelectList="relationUserDefaultSelectList"
      selectType="multiple" :autoClose="false" title="关联用户" businessUrl="/permission/userController"
      :option="relationUserOption" :submitBtnLoading="relationUserSubmitLoading" @submit="relationUserSubmit">
      <template #footer-left>已选人员：{{
        relationUserDefaultSelectList.map((item) => item.name).join('、')
      }}</template>
    </basic-dialog-table>
  </el-container>
</template>

<script setup>
import {
  apiGetMenuList,
  apiRelationMenu,
  apiGetUserListByRole,
  apiRelationUser,
  apiGetMenuListByRole,
} from '@/apis/permission/roleManage'

const basicCrudRef = ref()
const option = ref({
  menuWidth: 200,
  searchSpan: 6,
  viewBtn: true,
  column: [
    {
      label: '角色编码',
      prop: 'code',
      search: true,
      width: 160,
      rules: [
        {
          required: true,
          message: '编号不能为空',
          trigger: 'blur',
        },
      ],
      span: 24,
    },
    {
      label: '角色名称',
      prop: 'name',
      search: true,
      sortable: 'custom',
      width: 200,
      rules: [
        {
          required: true,
          message: '名称不能为空',
          trigger: 'blur',
        },
      ],
      span: 24,
    },
    {
      prop: 'roleType',
      label: '角色类型',
      width: 140,
      rules: [
        {
          required: true,
          message: '角色类型不能为空',
          trigger: 'blur',
        },
      ],
      type: 'select',
      dicCode: 'roleType',
      dicData: [
        {
          label: '管理类角色',
          value: 'manage',
        },
        {
          label: '业务类角色',
          value: 'bus',
        },
      ],
      maxLength: '240',
      span: 24,
    },
    {
      prop: 'des',
      label: '描述',
      rule: [],
      type: 'textarea',
      value: '',
      span: 24,
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      display: false,
      statusTag: true,
      fixed: 'right',
      width: 100,
    },
  ],
})

// 关联菜单
const useRelationMenu = () => {
  const relationMenuVisible = ref(false)
  const relationMenuOpenBtnLoading = ref(false)
  const relationMenuSubmitLoading = ref(false)
  const menuList = ref([])
  const menuTreeRef = ref()
  const selectedMenuList = ref([])
  const relationMenuParams = reactive({
    targetDatas: [],
    sourceDatas: [],
  })
  const relationMenuOption = {
    height: 400,
    menu: false,
    searchSpan: 8,
    header: false,
    column: [
      {
        label: '角色编码',
        prop: 'code',
        sortable: true,
        width: 230,
        search: true,
      },
      {
        label: '角色名称',
        prop: 'name',
        width: 200,
        sortable: true,
        search: true,
      },
      {
        label: '描述',
        sortable: true,
        prop: 'des',
        type: 'textarea',
        span: 24,
      },
    ],
  }
  const relationMenuDefaultSelectList = ref([])
  // 打开弹窗
  const handleOpenRelationMenuDialog = async () => {
    const { selectData } = basicCrudRef.value
    if (selectData.length !== 1) {
      return ElMessage.error('请选择一条数据进行操作！')
    }
    relationMenuParams.sourceDatas = selectData
    menuList.value = await apiGetMenuList(relationMenuOpenBtnLoading)
    const defaultSelectList = await apiGetMenuListByRole(selectData[0]['id'], relationMenuOpenBtnLoading)
    relationMenuVisible.value = true
    nextTick(() => setTreeSelected(defaultSelectList || []))
  }
  // 设置菜单选中数据
  const setTreeSelected = (list) => {
    const ids = list.map((item) => item.id)
    ids.forEach((id) => {
      let node = menuTreeRef.value.getNode(id)
      if (node) {
        node.expanded = true
        menuTreeRef.value.setChecked(node, true)
      }
    })
  }
  // 菜单选中
  const handleMenuSelectChange = (
    curNodeData,
    { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }
  ) => {
    selectedMenuList.value = checkedNodes
    relationMenuParams.targetDatas = checkedNodes
  }
  // 确定按钮
  const handleRelationMenuSubmit = async () => {
    if (selectedMenuList.value.length === 0) {
      return ElMessage.warning('请选择关联数据！')
    }
    await apiRelationMenu(relationMenuParams, relationMenuSubmitLoading)
    relationMenuSubmitLoading.value = false
    ElMessage.success('关联角色成功！')
    relationMenuVisible.value = false
    basicCrudRef.value.getList()
  }
  return {
    relationMenuVisible,
    relationMenuOption,
    handleOpenRelationMenuDialog,
    relationMenuOpenBtnLoading,
    handleRelationMenuSubmit,
    relationMenuDefaultSelectList,
    menuList,
    menuTreeRef,
    handleMenuSelectChange,
    relationMenuSubmitLoading,
  }
}

// 关联用户
const useRelationUser = () => {
  const relationUserVisible = ref(false)
  const relationUserOpenBtnLoading = ref(false)
  const relationUserSubmitLoading = ref(false)
  const relationUserOption = {
    dialogWidth: '80%',
    height: 400,
    menu: false,
    searchSpan: 8,
    header: false,
    reserveSelection: true,
    column: [
      {
        label: '账号',
        prop: 'code',
        sortable: true,
        width: 120,
        search: true,
      },
      {
        label: '姓名',
        prop: 'name',
        width: 120,
        sortable: true,
        search: true,
      },

      {
        label: '所属部门',
        prop: 'deptIdName',
        search: true,
        sortable: true,
      },
      {
        label: '职务',
        prop: 'dutyIdName',
        sortable: true,
      },
      {
        label: '移动电话',
        prop: 'mobile',
        sortable: true,
        search: true,
      },
      {
        label: '性别',
        prop: 'sex',
        sortable: true,
        formatter: (val) => {
          return val.sexText
        },
      },
      {
        label: '状态',
        sortable: true,
        width: 90,
        statusTag: true,
        prop: 'status',
        fixed: 'right',
      },
    ],
  }
  const relationUserParams = reactive({
    sourceDatas: [],
    targetDatas: [],
  })
  const relationUserDefaultSelectList = ref([])
  // 打开弹窗
  const handleOpenRelationUserDialog = async () => {
    const { selectData } = basicCrudRef.value
    if (selectData.length !== 1) {
      return ElMessage.error('请选择且只能选择一条数据！')
    }
    relationUserParams.sourceDatas = selectData
    relationUserOpenBtnLoading.value = true
    const defaultSelect = await apiGetUserListByRole(selectData[0]['id'])
    relationUserDefaultSelectList.value = defaultSelect || []
    relationUserOpenBtnLoading.value = false
    relationUserVisible.value = true
  }
  // 弹窗确定
  const relationUserSubmit = async (targetDatas) => {
    relationUserParams.targetDatas = targetDatas
    await apiRelationUser(relationUserParams, relationUserSubmitLoading)
    relationUserVisible.value = false
    ElMessage.success('关联成功！')
    basicCrudRef.value.getList()
  }
  return {
    relationUserVisible,
    relationUserOption,
    handleOpenRelationUserDialog,
    relationUserOpenBtnLoading,
    relationUserSubmit,
    relationUserDefaultSelectList,
    relationUserSubmitLoading,
  }
}

const {
  relationMenuVisible,
  relationMenuOption,
  handleOpenRelationMenuDialog,
  relationMenuOpenBtnLoading,
  handleRelationMenuSubmit,
  menuList,
  menuTreeRef,
  relationMenuDefaultSelectList,
  handleMenuSelectChange,
  relationMenuSubmitLoading,
} = useRelationMenu()

const {
  relationUserVisible,
  relationUserOption,
  handleOpenRelationUserDialog,
  relationUserOpenBtnLoading,
  relationUserSubmit,
  relationUserDefaultSelectList,
  relationUserSubmitLoading,
} = useRelationUser()
</script>

<style lang="scss" scoped></style>
